<?php

/*

COMP 353F
Dr. B Desai
Final Project
Group #11

6330746 Nicholas CONSTANTINIDIS
9532862 Jacqueline FU
5484537 Claudio Javier LOPEZ FLORES
9218416 Que Tung NGUYEN

*/

  session_start();
?>

<!DOCTYPE html>
<html lang="en">
<head>
        <title>CoBAGSys - Home</title>
        <link type="text/css" rel="stylesheet" href="css/mystyle.css">
        <script type="text/JavaScript" src="js/validate.js"></script>
        <script type="text/JavaScript">
        <!--
        function ValidateFields() {
	        return ValidateFieldNotEmpty("slick-login", "pname", "posting name")
	        && ValidateFieldNotEmpty("slick-login", "price", "price")
	        && ValidateFieldNumeric("slick-login", "price", "price")
	        && ValidateFieldNotEmpty("slick-login", "pcity", "posting city")
	        && ValidateFieldNotEmpty("slick-login", "description", "description")
	        && ValidateCheckboxChecked("slick-login", "agreement", "You must agree to the legal disclaimer in order to post");
        }
        //-->
        </script>
</head>
<body>
    <?php
      require 'menus.php';
    ?>
    <?php
        // Get the last posting ID of the currently logged in member
		function getNewPostingID() {
			$db = new Connect();
			
			$sql = "SELECT pID " .
				   "FROM Posting " .
			       "WHERE mID = " . $_SESSION['mid'] .
			       " ORDER BY pDatetime DESC " .
			       "LIMIT 1";
				   
			$result = $db->query($sql);
			
			if(!$result || mysql_num_rows($result) == 0) // Couldn't find posting
			{
				return;
			}
			else // Return posting info
			{
				$rows = $db->to_array($result);
				return $rows[0]['pID'];
			}
		}
		
		// Upload the given file
		function uploadfile() {
			if (!isset($_FILES["image"]) || $_FILES["image"]["error"] > 0)
			{
				return "";
			}
			else
			{
				if (!file_exists("img/" . $_FILES["image"]["name"]))
					move_uploaded_file($_FILES["image"]["tmp_name"], "img/" . $_FILES["image"]["name"]);
				
				return "./img/" . $_FILES["image"]["name"];
   			}
		}
		
		// Create the new posting
		function createposting() {
			$db = new Connect();
			
			$imageurl = uploadfile();			
			$pname = $_POST['pname'];
			$price = $_POST['price'];
			$cid = $_POST['cid'];
			$type = $_POST['type'];
			$pcity = $_POST['pcity'];
			$dcity = $_POST['dcity'];
			$desc = $_POST['description'];
			$status = "Open";
			
			// Set the default image if blank
			if ($imageurl == "")
				$imageurl = "./img/noimage.png";
				
			// Set the price to 0 and status barter if type barter
			if ($type == "barter")
			{
				$price = 0;
				$status = "Barter";
			}
			
			$sql = "INSERT INTO Posting(img, pCity, displayCity, mID, pName, pDesc, price, pDatetime, cID, status)" .
					"VALUES('" . $imageurl . "', '" . $pcity . "', '" . $dcity . "', " . $_SESSION['mid'] . ", '" . $pname . "', '" . $desc . "', " . $price . ", '" . date("Y-m-d H:i") . "', " . $cid . ", '" . $status . "')";
			
			$result = $db->query($sql);
			
			if(!$result || mysql_affected_rows() == 0) // Failed creating new posting
			{
				return false;
			}
			else // New posting created
			{
				// Redirect user to new posting
				print "<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=posting.php?pid=" . getNewPostingID() . "\">";
				
				return true;
			}
		}
		
		// Check to see if we received post data and perform posting
		$posting_failed = false;
		if (isset($_POST["post"]) && isset($_POST["agreement"]))
			$posting_failed = !createposting();			
    ?>
    <div id="main">
		<form id="slick-login" action="" onsubmit="return ValidateFields();" method="post" enctype="multipart/form-data">
	    	<p class="title">
	    		Create a new posting
	    	</p>
<?php
	if ($posting_failed == true)
		print "<p></p><span class=\"error\">FAILED TO CREATE POSTING!</span>";
?>
	        <input type="text" name="pname" placeholder="Posting Name">
<?php
	$rows = getCategoriesForMenu();
	
	if (isset($rows))
	{
		$rowcount = count($rows);
		print "<span class=\"normal\">Category:</span> <select name=\"cid\">";
		for ($i = 0; $i < $rowcount; $i++)
		{
			print "<option value=\"" . $rows[$i]['cid'] . "\">" . $rows[$i]['cName'] . "</option>";
		}
		print "</select>";
	}
?>	 
			<span class="normal">Type:</span>
			<select name="type">
				<option value="bid">Sell</option>
				<option value="barter">Barter</option>
			</select>
			<span class="normal"><br/>Image:</span>
			<input type="file" size="44" name="image" placeholder="Image">
	        <input type="text" name="price" placeholder="Price">
	        <input type="text" name="pcity" placeholder="Posting city">
	        <input type="text" name="dcity" placeholder="Display city">
			<textarea rows="15" cols="58" name="description" placeholder="Description"></textarea>
	    	<p class="title">
	    		Legal disclaimer
	    	</p>
			<p class="normal">
				Before posting, you must agree to the following terms: <br/>
				<ul class="legal">
					<li>Members are solely responsible for the contents of their postings.</li>
					<li>Items or services posted must not violate any applicable laws or regulations.</li>
					<li>Members may not barter, sell or give away items that require a written contract.</li>
					<li>Members may not barter, sell or give away items that are illegal.</li>
					<li>Members may not barter, sell or give away items that require a license to purchase or sell.</li>
					<li>Members must not post any unlawful, harassing, libelous, abusive, threatening, harmful, vulgar, obscene or otherwise objectionable material or services.</li>
				</ul>
			</p>
			<span class="legal">
				Members found in breach of this agreement will have some or all of their postings removed or modified. Members with repeated or egregious offenses may find their posting privileges suspended or removed at our discretion.
			</span>
			<p>
				<input type="checkbox" name="agreement" value="I agree">I agree to the above terms.
			</p>
			<p></p>
			<input type="submit" name="post" value="     Post    "/>
        </form>
    </div>
</body>
</html>
